package cn.actoncode.boot.framework.common.http;

import cn.actoncode.boot.framework.common.exception.PlatformError;
import cn.actoncode.boot.framework.common.exception.ServiceErrorException;
import cn.actoncode.boot.framework.common.http.apache.ApacheSimplePostRequestExecutor;
import cn.actoncode.boot.framework.common.http.enums.PlatformType;
import cn.actoncode.boot.framework.common.http.okhttp.OkHttpSimplePostRequestExecutor;

import jakarta.validation.constraints.NotNull;
import java.io.IOException;
import java.util.Map;

/**
 * 简单的POST请求执行器，请求的参数是String, 返回的结果也是String
 *
 * @author bin
 */
public abstract class SimplePostRequestExecutor<H, P> implements RequestExecutor<String, String> {
    protected RequestHttp<H, P> requestHttp;

    public SimplePostRequestExecutor(RequestHttp requestHttp) {
        this.requestHttp = requestHttp;
    }

    @Override
    public void execute(String uri, Map<String, String> headers, String data, ResponseHandler<String> handler, PlatformType platformType)
            throws ServiceErrorException, IOException {
        handler.handle(this.execute(uri, headers, data, platformType));
    }

    public static RequestExecutor<String, String> create(RequestHttp requestHttp) {
        switch (requestHttp.getRequestType()) {
            case APACHE_HTTP:
                return new ApacheSimplePostRequestExecutor(requestHttp);
            case OK_HTTP:
                return new OkHttpSimplePostRequestExecutor(requestHttp);
            default:
                throw new IllegalArgumentException("非法请求参数");
        }
    }

    @NotNull
    public String handleResponse(PlatformType platformType, String responseContent) throws ServiceErrorException {
        if (responseContent.isEmpty()) {
            throw new ServiceErrorException("无响应内容");
        }

        PlatformError error = PlatformError.parse(responseContent, platformType);
        if (error.getErrorCode() != platformType.getCode()) {
            throw new ServiceErrorException(error);
        }
        return responseContent;
    }
}
